package com.quectel.business.common.grid;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.core.grid.GridMemberEvaluateConstant;
import com.quectel.core.module.grid.dto.GridEventRecordDto;
import com.quectel.core.module.grid.dto.GridMemberDto;
import com.quectel.core.module.grid.dto.GridMemberEvaluateDto;
import com.quectel.core.module.grid.service.GridEventRecordService;
import com.quectel.core.module.grid.service.GridMemberEvaluateService;
import com.quectel.core.module.grid.service.GridMemberService;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在这里编写说明
 *
 * @author: bob
 * @email: bob.yu@quectel.com
 * @date: 2023-02-13 10:46:00
 */
@Component
public class GridMemberEvaluateBusiness {

    @DubboReference
    private GridMemberService gridMemberService;
    @DubboReference
    private GridMemberEvaluateService gridMemberEvaluateService;
    @DubboReference
    private GridEventRecordService gridEventRecordService;

    /**
     * 根据租户id以及选择的评估年份生成评估记录
     *
     * @param tenantId
     * @param assessYear 1.根据租户查询网格员
     *                   2.根据网格员列表生成对应的年份记录 (可重复生成，已经生成的不受影响)
     */
    public void generateEvaluateRecord(Long tenantId, String assessYear) {

        String recordYear = assessYear + "-01-01";
        Map<String, Object> gridMemberMap = new HashMap<>();
        gridMemberMap.put(LambdaUtil.getFieldName(GridMemberDto::getTenantId), tenantId);
        List<GridMemberDto> gridMemberDtos = gridMemberService.queryList(gridMemberMap);
        if (CollectionUtils.isEmpty(gridMemberDtos)) {
            return;
        }
        for (GridMemberDto gridMember : gridMemberDtos) {
            Long gridMemberId = gridMember.getId();
            // 判断用户是否生成过记录
            GridMemberEvaluateDto evaluate = gridMemberEvaluateService.selectOneByMemberIdAndAssessYear(gridMemberId, assessYear);
            if (evaluate == null) {
                GridMemberEvaluateDto addly = new GridMemberEvaluateDto();
                addly.setTenantId(tenantId);
                addly.setGridMemberId(gridMemberId);
                addly.setAssessYear(assessYear);
                addly.setAssessResult(GridMemberEvaluateConstant.EvaluateResult.INIT.getType());
                addly.setCreateTime(new Date());

                Map<String, Object> sqlMap = new HashMap<>();
                sqlMap.put(LambdaUtil.getFieldName(GridEventRecordDto::getGridMemberId), gridMemberId);
                sqlMap.put("startTime", DateUtils.format(DateUtil.beginOfYear(DateUtil.parseDate(recordYear)), DateUtils.FormatType.COMMON));
                sqlMap.put("endTime", DateUtils.format(DateUtil.endOfYear(DateUtil.parseDate(recordYear)), DateUtils.FormatType.COMMON));
                // 总的处理的事件
                List<GridEventRecordDto> totalList = gridEventRecordService.queryList(sqlMap);

                int total = totalList.size();
                // 办结
                int finishedTotal = (int) totalList.stream()
                        .filter(item -> item.getStatus().equals(GridConstant.GridEventRecordStatus.FINISHED.getStatus())).count();
                // 驳回
                int rejectedTotal = (int) totalList.stream()
                        .filter(item -> item.getStatus().equals(GridConstant.GridEventRecordStatus.REJECTED.getStatus())).count();
                // 逾期
                int expiredTotal = (int) totalList.stream()
                        .filter(item -> item.getStatus().equals(GridConstant.GridEventRecordStatus.EXPIRED.getStatus())).count();
                // 事件json留存
                Map<String, Object> jsonObject = new HashMap<>(4);
                jsonObject.put("total", total);
                jsonObject.put("finishedTotal", finishedTotal);
                jsonObject.put("rejectedTotal", rejectedTotal);
                jsonObject.put("expiredTotal", expiredTotal);
                addly.setAssessRecordJson(JacksonUtils.toJsonString(jsonObject));

                gridMemberEvaluateService.save(addly);
            }
        }
    }
}
